package com.bjb.vr.common.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjb.vr.common.constant.LoginConstant;
import com.bjb.vr.common.constant.ThreadLocalConstant;
import com.bjb.vr.common.dto.SysLogin;
import com.bjb.vr.common.dto.UmsAccount;
import com.bjb.vr.common.dto.UmsOptAccount;
import com.bjb.vr.common.mapper.SysLoginMapper;
import com.bjb.vr.common.utils.ThreadLocalUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author admin
 * @description
 * @createDate 2022-07-26 13:18:12
 */
@Service
public class SysLoginService extends ServiceImpl<SysLoginMapper, SysLogin> {

    @Resource
    private SysLoginMapper sysLoginMapper;

    @Resource
    private UmsAccountService accountService;

    @Resource
    private UmsOptAccountService optAccountService;

    /**
     * 保存用户登录信息
     *
     * @param sysLogin
     */
    public void saveLoginInfo(SysLogin sysLogin) {
        try {
            sysLoginMapper.insert(sysLogin);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 获取登录用户信息
     *
     * @param username
     * @param loginType
     * @return
     */
    public Map<String, Object> queryUserInfo(String username, String loginType) {
        ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, true);
        Map<String, Object> userInfo = new HashMap<>();
        if (LoginConstant.MANAGER.equals(loginType)) {
            UmsAccount account = accountService.getAccountByUsername(username);
            if (Objects.nonNull(account)) {
                userInfo.put(ThreadLocalConstant.TENANT_ID, account.getTenantId());
                userInfo.put(ThreadLocalConstant.USER_ID, account.getId());
            }
        } else {
            UmsOptAccount optAccount = optAccountService.getAccountByUsername(username);
            if (Objects.nonNull(optAccount)) {
                userInfo.put(ThreadLocalConstant.TENANT_ID, optAccount.getTenantId());
                userInfo.put(ThreadLocalConstant.USER_ID, optAccount.getId());
            }
        }
        return userInfo;
    }
}




